package com.rising.nio;

import java.util.Arrays;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2020/8/27 23:12
 */
public class ArrayShun2 {
    public static void main(String[] args) {
        //定义一个5行4列的数组
       /* int[][] array = {{1 , 2, 3, 4},
                         {5 , 6, 7, 8},
                         {9 ,10,11,12},
                         {13,14,15,16},
                         {17,18,19,20}};*/
        /*int[][] array = {{1 , 2, 3, 4},
                         {5 , 6, 7, 8},
                         {9 ,10,11,12}};*/
        /*int[][] array = {{1 , 2, 3},
                        {5 , 6, 7}};*/
        int[][] array = {{1},{2}};
        /*int[] rtnArray = new int[array.length * array[0].length];
        printArray(0, 0, array, rtnArray, 0);
        System.out.println(rtnArray);*/
        Solution2 solution2 = new Solution2();
        int[] ints = solution2.spiralOrder(array);
        System.out.println(Arrays.asList(ints));
    }
}

class Solution2 {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0) {
            return new int[0];
        }
        if (matrix.length == 1) {
            return matrix[0];
        }
        int[] rtnArray = new int[matrix.length * matrix[0].length];
        this.printArray(0, 0, matrix, rtnArray, 0);
        return rtnArray;
    }
    private void printArray(int x, int y, int[][] array, int[] rtnArray, int index) {
        int xStart = x;
        int yStart = y;
        if ((x > array.length/2) || (y > array[0].length/2) || (x == array.length - 1 && x != 0) || (y == array[0].length - 1 && y !=0)) {
            return;
        }

        boolean flag = true;
        if ((array.length % 2 !=0 && x == array.length/2) || (array[0].length % 2 !=0 && y == array[0].length/2)) {
            flag = false;
        }

        //打印上边
        for (; y < array[0].length - yStart; y++) {
            rtnArray[index++] = array[x][y];
        }

        //打印右边
        for (x = x + 1; x < array.length - xStart; x++) {
            rtnArray[index++] = array[x][y - 1];
        }

        if (flag) {
            //打印下边
            for (y = y - 2; y >= yStart; y--) {
                rtnArray[index++] = array[x - 1][y];
            }

            //打印左边
            for (x = x - 2; x > xStart; x--) {
                rtnArray[index++] = array[x][y + 1];
            }
        }

        printArray(xStart + 1, yStart + 1, array, rtnArray, index);
    }
}
